package com.loklok.code.confuse.util;

import com.alibaba.fastjson.JSONArray;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.project.Project;
import com.intellij.util.ExceptionUtil;
import com.loklok.code.confuse.action.OpenPathConfigSettingAction;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Classname CommonUtil
 * @Description
 * @Date 2023/5/8 14:15
 * @author wangchangjiu
 */
public class CommonUtil {

    public static final String DEFAULT_PROMPT = "请给出 [%s] 这些单词的英文同义词，要求每个单词的同义词返回5个，结果案例如下形式: {'appBundleID':['appBundleID1', 'appBundleID2'], 'keyIdentifier':['keyIdentifier1', 'keyIdentifier2']},只返回压缩的json，请注意不需要其他解释";

    private static Pattern UNDERLINE_PATTERN = Pattern.compile("_([a-z])");

    private static Pattern QUOTATION_MARK_PATTERN = Pattern.compile("\\`(.*?)\\`");

    public static final String SEPARATOR = "_";

    public static void configureMessageReminders(Project project) {
        Notification notification = new Notification("Print", "confuseSetting",
                "检查到有未完成的配置", NotificationType.INFORMATION);
        // 在提示消息中，增加一个 Action，可以通过 Action 一步打开配置界面
        notification.addAction(new OpenPathConfigSettingAction("打开配置界面" ));
        Notifications.Bus.notify(notification, project);
    }


    /**
     * 将下划线形式的字符串转换为驼峰形式。
     * @param underscoreStr 下划线形式的字符串
     * @return 转换后的驼峰形式字符串 并且 首字母大写
     */
    public static String pckToClassPrefix(String underscoreStr) {
        if (underscoreStr == null || underscoreStr.isEmpty()) {
            return underscoreStr;
        }

        StringBuilder camelStrBuilder = new StringBuilder();
        boolean nextUpperCase = false;

        for (char c : underscoreStr.toCharArray()) {
            if (c == '_') {
                nextUpperCase = true;
            } else {
                if (nextUpperCase) {
                    camelStrBuilder.append(Character.toUpperCase(c));
                    nextUpperCase = false;
                } else {
                    camelStrBuilder.append(c);
                }
            }
        }
        return new StringBuilder().append(Character.toUpperCase(camelStrBuilder.charAt(0))).append(camelStrBuilder.substring(1)).append("").toString();
    }


    private static <T> List<T> readAndParseConfig(Path path, Class<T> clazz){
        try {
            // 从配置文件中加载配置
            String json = Files.readString(path, StandardCharsets.UTF_8);;
            return JSONArray.parseArray(json, clazz);
        } catch (Exception e) {
            ExceptionUtil.rethrow(e);
        }
        return new ArrayList<>();
    }

    public static String dropQuotationMark(String name){
        if(name == null || name.length() == 0){
            return name;
        }
        Matcher matcher = QUOTATION_MARK_PATTERN.matcher(name);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return name;
    }

    public static String underlineToHump (String str, boolean titleCase){
        if(str == null || str.length() == 0){
            return str;
        }
        str = str.toLowerCase();
        Matcher matcher = UNDERLINE_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(0).toUpperCase());
        }
        matcher.appendTail(sb);
        if(titleCase){
            sb.setCharAt(0, (char) ((int)sb.charAt(0) - 32));
        }
        return sb.toString().replaceAll("_", "");
    }

    public static String pathToPackage(String fullPath){
        if (!StringUtils.isEmpty(fullPath)) {
            return fullPath.replace("/", ".");
        }
        return fullPath;
    }

    public static String pathJoint(String ...path){
        return String.join("/", path);
    }

    public static String pathToImportPackage(String fullPath){
        String fullPackage = "";
        if (!StringUtils.isEmpty(fullPath)) {
            fullPackage = fullPath.replace("/", ".");
        }
        fullPackage = fullPackage.replace("src.main.java.", "import ");
        return fullPackage + ".*;";
    }

    public static String pathToDeclarePackage(String fullPath){
        String fullPackage = "";
        if (!StringUtils.isEmpty(fullPath)) {
            fullPackage = fullPath.replace("/", ".");
        }
        fullPackage = fullPackage.replace("src.main.java.", "");
        return fullPackage;
    }

    /**
     * 根据全类名获取类名
     *
     * @param fullClassName 全类名
     * @return 类名
     */
    public static String getClassNameByFullClassName(String fullClassName) {
        String className = StringUtils.substringAfterLast(fullClassName, ".");
        return StringUtils.isNotBlank(className) ? className : fullClassName;
    }

    /**
     * 根据全类名获取包名
     *
     * @param fullClassName 全类名
     * @return 包名
     */
    public static String getPackageNameByFullClassName(String fullClassName) {
        return StringUtils.substringBeforeLast(fullClassName, ".");
    }

   // private static final String VO_REGEX = "\\$!\\{vo\\.([a-zA-Z_][a-zA-Z0-9_]*)\\}";
  //  private static Pattern VO_PATTERN = Pattern.compile(VO_REGEX);

   // private static final String REQUEST_REGEX = "\\$!\\{request\\.([a-zA-Z_][a-zA-Z0-9_]*)\\}";
   // private static Pattern REQUEST_PATTERN = Pattern.compile(REQUEST_REGEX);

    private static final String VO_REGEX = "\\$!\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}";
    private static Pattern PARAM_PATTERN = Pattern.compile(VO_REGEX);

    public static Set<String> regularExtractParams(String content){
        Matcher matcher = PARAM_PATTERN.matcher(content);

        Set<String> params = new HashSet<>();
        // 查找并提取所有匹配的内容
        while (matcher.find()) {
            String extracted = matcher.group(1); // 提取括号内的内容
            params.add(extracted);
        }

        return params;
    }

    public static String getParentDirectoryName(String realPath){
        Path path = Paths.get(realPath);
        // 获取父目录的路径
        Path parentPath = path.getParent();
        // 获取父目录的名称
        String directoryName = parentPath.getFileName().toString();
        return directoryName;
    }

    public static void main(String[] args) {
       System.out.println( underlineToHump("too", false));
    }

}
